import {handlePieChart} from "../../utils/handleEcharts";
import dayjs from "dayjs";
import {exportWordDocx} from "../../utils/exportWordDocx";
import constants from "../../utils/constants";
import {getPercent, handleSheetData} from "../../utils/askAi";
import {askAi} from "@/api/askAi.js"
import {sleep} from "@/utils/askAi.js"
import {uploadReport} from "../../utils/uploadReport";


let {QTLX, MBZL, SXJK, XYZB, GJLX, OTHER, XD, THSJ, ZXLX, GDMS, xueduanOrder} = constants;

export async function exportWeek(dataArr) {
    //处理招生政策分类和所属区域分类
    let xueduanArr;
    let areaArr;

    function handleData(sheetContent) {
        let {xueduanLists, areaLists} = handleSheetData(sheetContent);
        xueduanArr = xueduanLists;
        areaArr = areaLists;
    }

    //获取开始时间和结束时间
    function setDate() {
        dataArr.sort((a, b) => new Date(a[THSJ]) - new Date(b[THSJ]));
        let startDate = dataArr[0][THSJ];
        let endDate = dataArr[dataArr.length - 1][THSJ];
        if (startDate.split("-")[0] !== endDate.split("-")[0]) {
            startDate = dayjs(startDate).format("YYYY年M月D日");
            endDate = dayjs(endDate).format("YYYY年M月D日");
        } else {
            startDate = dayjs(startDate).format("M月D日");
            endDate = dayjs(endDate).format("M月D日");
        }
        return {startDate, endDate};
    }

    //一、总体情况
    function handleTotal() {
        let totalText = `局信访办共受理群众来电${dataArr.length}件，其中“民呼我为”办件  件，平台共接到电话${dataArr.length}个。其中`;

        let arr1 = [];

        function appendIfNonEmpty(arr, label, unit) {
            if (arr.length > 0) {
                let str = `${label}问题${arr.length}${unit}`;
                arr1.push(str);
            }
        }

        for (let item in xueduanArr) {
            appendIfNonEmpty(xueduanArr[item], item, "条");
        }
        totalText += arr1.join("，")
        return totalText;
    }

    //二、主要问题
    async function setMainQuestion() {
        let questionList = {
            question: [],
            [QTLX]: [],
            [MBZL]: [],
            [SXJK]: [],
            [XYZB]: []
        };
        dataArr.forEach(item => {
            if (item[ZXLX]) {
                let lxList = item[ZXLX].split(",");
                lxList.forEach(i => {
                    if (!questionList[i]) {
                        questionList[i] = [];
                    }
                    questionList[i].push(item);
                });
            } else {
                questionList.question.push(item);
            }
        });
        let index = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
        let mainQuestion = [];
        let questions = []
        for (let key in questionList) {
            let text = "";
            let title = "";
            let prompt = "";
            if (key === "question") {
                let xueduanList = [];
                for (let key in xueduanArr) {
                    if (xueduanArr[key].length > 0 && key !== OTHER) {
                        xueduanList.push({
                            name: key,
                            value: xueduanArr[key].length,
                            questions: xueduanArr[key].map(i => i[GDMS])
                        });
                    }
                }
                xueduanList.sort((a, b) => b.value - a.value);
                title = `咨询${xueduanList[0].name}、${xueduanList[1].name}学校等学籍和转学问题`;
                prompt = `以上数组是家长关于学生学籍和转学问题发起的咨询，根据以下要求总结问题：1，总结这些问题主要集中在哪个方面。2，总结两到三个主要的具体问题。3，以‘学籍和转学的咨询集中在……方面，一是……，二是……’的格式总结问题。3，直接输出结果不要返回其他内容。`;
                questions = xueduanList.map(i => i.questions)
            } else if (key === QTLX) {
                title = "其他主要涉及问题";
                prompt = `以上数组是家长关于学生的一些问题发起的反馈，根据以下要求总结这些问题：1，总结2到3个主要的具体问题。2，简单概括问题，格式如“投诉……问题”。3，用分号隔开问题类型，不要序号，不要换行。4，直接输出结果不要返回其他内容`;
                questions = questionList[key].map(i => i[GDMS])
            } else {
                title = key;
                prompt = `以上数组是家长关于学生${key}问题发起的咨询，根据以下要求总结这些问题：1，将以上问题简单分为最多5类。2，简单概括问题类型，格式如“咨询……问题”。3，用分号隔开问题类型，不要序号，不要换行。4，直接输出结果不要返回其他内容`;
                questions = questionList[key].map(i => i[GDMS])
            }
            await sleep(1000)
            if (questions.length === 0) {
                text = ""
            } else {
                text = await askAi(JSON.stringify(questions) + prompt);
            }
            mainQuestion.push({title, text});
        }
        for (let i = 0; i < mainQuestion.length; i++) {
            mainQuestion[i].index = index[i];
        }

        return mainQuestion;
    }

//地区占比分析
    function setAreaData(sheetContent) {
        let areaData = [];
        for (let key in areaArr) {
            if (areaArr[key].length > 0) {
                areaData.push({
                    name: key,
                    value: areaArr[key].length,
                    percent: getPercent(areaArr[key], sheetContent)
                });
            }
        }
        //处理所属区域总结性内容
        let areaText = "";
        areaData.sort((a, b) => {
            return b.value - a.value;
        });
        if (areaData.length > 1) {
            areaText = `各区（县、市）中，${areaData[0].name}和${areaData[1].name}咨询占比较多，分别为${areaData[0].percent}和${areaData[1].percent}。`;
        } else if (areaData.length > 0) {
            areaText = `各区（县、市）中，${areaData[0].name}咨询占比较多，为${areaData[0].percent}。`;
        }
        let areaImg = handlePieChart(areaData, "地区占比");
        return {areaText, areaImg};
    }

//学段占比分析
    function setXueduanData(sheetContent) {
        let xueduanList = [];
        for (let key in xueduanArr) {
            if (xueduanArr[key].length > 0) {
                xueduanList.push({
                    name: key,
                    value: xueduanArr[key].length,
                    percent: getPercent(xueduanArr[key], sheetContent)
                });
            }
        }
        xueduanList.sort((a, b) => {
            return xueduanOrder.indexOf(a.name) - xueduanOrder.indexOf(b.name);
        });
        let xueduanImg = handlePieChart(xueduanList, "学段占比");
        return {xueduanImg};
    }

//四、具体问题
    function handleQuestion() {
        let res = [];
        for (let key in xueduanArr) {
            let questionLines = [];
            let sortArr = [];
            for (let i = 0; i < xueduanArr[key].length; i++) {
                const item = xueduanArr[key][i];
                sortArr.push(item[GDMS]);
                questionLines = sortArr.map((item, index) => `${index + 1}.${item}`);
            }
            const questions = questionLines.join("\n");
            res.push({name: key, questions});
        }
        return res;
    }

    dataArr.forEach(item => {
        if (item[GJLX]) {
            let arr = item[GJLX].split("&#10;");
            arr.forEach(i => {
                let key = i.split(":")[0];
                item[key] = i.split(":")[1];
            });
        }
    });

    handleData(dataArr);
    let {startDate, endDate} = setDate();
    let totalText = handleTotal();
    let xueduanData = setXueduanData(dataArr);
    let areaData = setAreaData(dataArr);
    let mainQuestion = await setMainQuestion();
    let questionList = handleQuestion();


    let fileName = `${startDate}-${endDate}信访来电服务平台周报`
    let arrayBuffer = await exportWordDocx(
        "/templateDocx/weekTemplate.docx",
        {
            startDate,
            endDate,
            totalText,
            ...xueduanData,
            ...areaData,
            mainQuestion,
            questionList
        },
        fileName + new Date().getTime()
    );

    let file = new File([arrayBuffer], fileName)
    // await uploadReport('weekly', fileName, file)
}
